import axios from 'axios'
import api from '@/api'

let http = axios.create({
  baseURL: '',
  timeout: 20 * 1000
})

http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'

// 请求拦截器
http.interceptors.request.use((config) => {
  // url处理
  config.url = process.env.VUE_APP_ROOT + config.url
  // 强制调用时传递method用大写
  let method = config.method || 'get'

  if (method !== 'get') {
    // 强制传递了method
  } else if (config.params) {
    config.method = 'get'
  } else if (config.data) {
    config.method = 'post'
  }

  let token = ''
  if (token) {
    config.headers.Token = token
  }

  // FormData
  if (config.data && typeof config.data.append === 'function') {
    config.headers['Content-Type'] = 'multipart/form-data'
    config.timeout = 60 * 1000
  }

  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
http.interceptors.response.use(response => {
  if (response.status === 200) {
    let data = response.data
    let Code = data.Code
    if (Code === api.CodeSuccess) {
      return Promise.resolve(data)
    } else {
      return Promise.reject(response)
    }
  } else {
    return Promise.reject(response)
  }
}, error => {
  return Promise.reject(error.response)
})

export default {
  // get请求
  get: function (url, params) {
    return http({
      method: 'GET',
      url: url,
      params: params
    })
  },
  // post请求
  post: function (url, data) {
    return http({
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      url: url,
      data: JSON.stringify(data)
    })
  }
}
